from flask import Blueprint, jsonify
from sqlalchemy import func, and_, or_
from datetime import datetime, timedelta
from ..models import db, WorkOrder, User, Vehicle, Material, MaterialUsage
from ..utils.auth import require_permission, get_current_user

dashboard_bp = Blueprint('dashboard', __name__, url_prefix='/dashboard')

@dashboard_bp.route('/stats', methods=['GET'])
@require_permission('dashboard.view')
def get_dashboard_stats():
    """获取仪表板统计数据"""
    try:
        current_user = get_current_user()
        
        # 工单统计
        work_order_query = db.session.query(WorkOrder)
        
        # 根据用户角色过滤数据
        if current_user.role == 'user':
            work_order_query = work_order_query.filter(
                or_(
                    WorkOrder.creator_id == current_user.id,
                    WorkOrder.assignee_id == current_user.id
                )
            )
        elif current_user.role == 'manager' and current_user.group_id:
            # 管理员可以看到自己组的工单
            work_order_query = work_order_query.join(User, WorkOrder.creator_id == User.id)
            work_order_query = work_order_query.filter(
                or_(
                    User.group_id == current_user.group_id,
                    WorkOrder.assignee_id == current_user.id
                )
            )
        
        # 统计工单数量
        total_work_orders = work_order_query.count()
        pending_work_orders = work_order_query.filter(WorkOrder.status == 'pending').count()
        in_progress_work_orders = work_order_query.filter(WorkOrder.status == 'in_progress').count()
        completed_work_orders = work_order_query.filter(WorkOrder.status == 'completed').count()
        
        # 人员统计
        personnel_query = db.session.query(User).filter(User.is_active == True)
        if current_user.role == 'manager' and current_user.group_id:
            personnel_query = personnel_query.filter(User.group_id == current_user.group_id)
        elif current_user.role == 'user':
            personnel_query = personnel_query.filter(User.id == current_user.id)
        
        total_personnel = personnel_query.count()
        
        # 车辆统计
        vehicle_query = db.session.query(Vehicle).filter(Vehicle.is_active == True)
        if current_user.role == 'manager' and current_user.group_id:
            vehicle_query = vehicle_query.filter(Vehicle.group_id == current_user.group_id)
        elif current_user.role == 'user':
            # 普通用户只能看到分配给自己的车辆
            vehicle_query = vehicle_query.filter(Vehicle.assignee_id == current_user.id)
        
        total_vehicles = vehicle_query.count()
        available_vehicles = vehicle_query.filter(Vehicle.status == 'available').count()
        
        # 材料统计
        material_query = db.session.query(Material).filter(Material.is_active == True)
        total_materials = material_query.count()
        low_stock_materials = material_query.filter(Material.stock_quantity <= Material.min_stock).count()
        
        # 最近7天的工单趋势
        seven_days_ago = datetime.utcnow() - timedelta(days=7)
        daily_stats = []
        
        for i in range(7):
            day = seven_days_ago + timedelta(days=i)
            day_start = day.replace(hour=0, minute=0, second=0, microsecond=0)
            day_end = day_start + timedelta(days=1)
            
            day_query = work_order_query.filter(
                and_(
                    WorkOrder.created_at >= day_start,
                    WorkOrder.created_at < day_end
                )
            )
            
            daily_count = day_query.count()
            daily_stats.append({
                'date': day.strftime('%Y-%m-%d'),
                'count': daily_count
            })
        
        # 工单状态分布
        status_distribution = [
            {'status': '待处理', 'count': pending_work_orders},
            {'status': '处理中', 'count': in_progress_work_orders},
            {'status': '已完成', 'count': completed_work_orders}
        ]
        
        # 优先级分布
        priority_stats = []
        for priority in ['high', 'medium', 'low']:
            count = work_order_query.filter(WorkOrder.priority == priority).count()
            priority_name = {'high': '高', 'medium': '中', 'low': '低'}.get(priority, priority)
            priority_stats.append({'priority': priority_name, 'count': count})
        
        return jsonify({
            'totalWorkOrders': total_work_orders,
            'pendingWorkOrders': pending_work_orders,
            'inProgressWorkOrders': in_progress_work_orders,
            'completedWorkOrders': completed_work_orders,
            'totalUsers': total_personnel,
            'totalVehicles': total_vehicles,
            'availableVehicles': available_vehicles,
            'totalMaterials': total_materials,
            'lowStockMaterials': low_stock_materials,
            'dailyTrend': daily_stats,
            'statusDistribution': status_distribution,
            'priorityDistribution': priority_stats
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'获取统计数据失败: {str(e)}'}), 500

@dashboard_bp.route('/recent-work-orders', methods=['GET'])
@require_permission('dashboard.view')
def get_recent_work_orders():
    """获取最近的工单"""
    try:
        current_user = get_current_user()
        
        # 构建查询
        query = db.session.query(WorkOrder).join(User, WorkOrder.creator_id == User.id)
        
        # 根据用户角色过滤数据
        if current_user.role == 'user':
            query = query.filter(
                or_(
                    WorkOrder.creator_id == current_user.id,
                    WorkOrder.assignee_id == current_user.id
                )
            )
        elif current_user.role == 'manager' and current_user.group_id:
            query = query.filter(
                or_(
                    User.group_id == current_user.group_id,
                    WorkOrder.assignee_id == current_user.id
                )
            )
        
        # 获取最近5条工单
        work_orders = query.order_by(WorkOrder.created_at.desc()).limit(5).all()
        
        result = []
        for wo in work_orders:
            result.append({
                'id': wo.id,
                'title': wo.title,
                'priority': wo.priority,
                'status': wo.status,
                'created_at': wo.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'creator_name': wo.creator.name if wo.creator else '未知',
                'assignee_name': wo.assignee.name if wo.assignee else '未分配'
            })
        
        return jsonify({'items': result}), 200
        
    except Exception as e:
        return jsonify({'error': f'获取最近工单失败: {str(e)}'}), 500